package com.bozhong.config;

import cn.hutool.core.util.NumberUtil;
import com.bozhong.config.common.ConfigSetPropertyHolder;
import com.bozhong.config.exception.ConfigException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Optional;

/**
 * @author fupan
 * @date 2021-04-20
 */
public class ConfigLoadListener implements ServletContextListener {
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext servletContext = sce.getServletContext();
		String serverAddr = Optional.ofNullable(servletContext.getInitParameter("serverAddr"))
				.orElseThrow(() -> new ConfigException(new NullPointerException("serverAddr不能为空")));
		String encode = servletContext.getInitParameter("encode");
		String group = servletContext.getInitParameter("group");
		int timeout = Optional.ofNullable(servletContext.getInitParameter("timeout"))
				.filter(NumberUtil::isInteger)
				.map(Integer::parseInt)
				.orElse(3000);
		String endpoint = servletContext.getInitParameter("endpoint");
		String namespace = servletContext.getInitParameter("namespace");
		String accessKey = servletContext.getInitParameter("accessKey");
		String secretKey = servletContext.getInitParameter("secretKey");
		String contextPath = servletContext.getInitParameter("contextPath");
		String clusterName = servletContext.getInitParameter("clusterName");
		String dataId = servletContext.getInitParameter("dataId");
		String fileExtension = servletContext.getInitParameter("fileExtension");
		ConfigSetPropertyHolder.builder()
				.serverAddr(serverAddr)
				.encode(encode)
				.group(group)
				.timeout(timeout)
				.endpoint(endpoint)
				.namespace(namespace)
				.accessKey(accessKey)
				.secretKey(secretKey)
				.contextPath(contextPath)
				.clusterName(clusterName)
				.dataId(dataId)
				.group(group)
				.fileExtension(fileExtension)
				.build()
				.init();
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}
}